# -*- coding: utf-8 -*-
# @Time    : 2018/12/14 9:17
# @Author  : yueconger
# @File    : ProposalAPI.py
# 对接java传递参数,生成新版本意见书
import os
import pymysql
import requests
import time
from DBUtils.PooledDB import PooledDB
from ConsultAPI.conf import xml_file, html_ex_path, html_path, xml_file_path_list
from ConsultAPI.handle_content import HandleContent, HunYin, Labor
from ConsultAPI.user_path2doc import Return_Report_Name


class Proposal(object):
    def __init__(self, uuid, pool):
        self.uuid = uuid
        self.report_html = 'http://182.254.134.202:5004/report/'
        self.pool = pool
        print('程序初始化...')

    def process_content(self):
        """
        通过uuid 向数据库中查询路径及所有相关信息
        :return: all_list 路径path的list列表
        """
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        print('当前时间: ', current_time)
        conn = self.pool.connection()
        cur = conn.cursor()
        sql = """
                select type, -- 1单选，2多选，3填空 
                        question_name, -- 问题名称
                        group_concat(case when type = 3 then COALESCE(answer_name, '@null@') else answer_name end separator '###') answers, -- 答案
                        group_concat(case when type = 3 then COALESCE(context, '@null@') else context end separator '###') contexts, -- 填空题具体答案，针对填空题有值
                        evaluation_root_id
                from api_evaluation
                where uuid = '%s' and skip_flag <> 1
                group by question_id
                order by orderby asc 
            """ % (self.uuid)
        try:
            res_db = cur.execute(sql)
        except:
            print('查询有误!')
        if res_db > 0:
            results = cur.fetchall()
            all_list = []
            for result in results:
                evaluation_root_id = result[-1]  # 纠纷类型
                result_item = {}
                result_item['iw'] = result[0]
                if result_item['iw'] == 1:
                    # 单选
                    result_item['id_question'] = result[1]
                    result_item['item'] = result[2]
                elif result_item['iw'] == 2:
                    # 多选 版本二
                    result_item_ex = []
                    items = result[2].split('###')
                    for i in items:
                        result_dict_ex = {}
                        result_dict_ex['iw'] = 2
                        result_dict_ex['id_question'] = result[1]
                        result_dict_ex['item'] = i
                        result_item_ex.append(result_dict_ex)
                    result_item = result_item_ex
                else:
                    # 填空
                    print('当前iw', result[0])
                    result_item['id_question'] = result[1]
                    items = result[2]
                    values = result[3]
                    result_item['item'] = items.split('###')
                    values_ex = values.split('###')
                    values_new = []
                    for n in values_ex:
                        if n == '@null@':
                            n = ''
                        values_new.append(n)
                    result_item['value'] = values_new
                all_list.append(result_item)
            dispute_type_id = evaluation_root_id
            sql_report = """
            select report_text from api_evaluation_tree tree
                inner join (select question_id,answer_id,orderby from api_evaluation where uuid = '%s' ) eva on
                eva.question_id = tree.tnode_id or eva.answer_id = tree.tnode_id
              where tree.report_text is not null
              group by tree.tnode_id
              order by eva.orderby DESC
            """%(self.uuid)
            try:
                res_report = cur.execute(sql_report)
            except:
                print('查询报告文件有误!')
            if res_report > 0:
                results = cur.fetchall()
                report_list = []
                for result in results:
                    report_id = result[0] + '.html'
                    report_list.append(report_id)
            return dispute_type_id, all_list, report_list
        else:
            print('uuid路径未找到')
            return None

    def obtain_report_ex(self, dispute_type, report_id):
        # 原始文件暂存目录
        # xxxxx.html
        print('report_id', report_id)
        report_html = os.path.join(self.report_html, dispute_type, report_id)
        print(report_html)
        response = requests.get(report_html)
        source_html_path = ''.join(['./ConsultAPI/source_html_ex/', report_id])
        with open(source_html_path, 'w', encoding='utf-8') as wf:
            wf.write(response.content.decode())
        return source_html_path

    def dispute_type(self, dispute_type_id):
        """
        寻找服务器纠纷类型文件地址暂处理方法
        :param dispute_type_id:
        :return:
        """

        for xml_file_dict in xml_file_path_list:
            if xml_file_dict['dispute_type_id'] == dispute_type_id:
                dispute_type = xml_file_dict['report_dispute_type']
                return dispute_type
        else:
            print('dispute_type_id is %s, 未找到相对应路径' % dispute_type_id)

    def xml_file_find(self, dispute_type_id):
        # 版本二 通过ID 自动查找
        for xml_file_dict in xml_file_path_list:
            if xml_file_dict['dispute_type_id'] == dispute_type_id:
                xml_file_path = xml_file_dict['xml_file_path']
                return xml_file_path
        else:
            print('dispute_type_id is %s, 未找到相对应路径' % dispute_type_id)

    def run(self):  # 待对接参数
        # 生成点击流程path路径
        dispute_type_id, user_path, report_id_list = self.process_content()
        dispute_type = self.dispute_type(dispute_type_id)
        print('dispute_type', dispute_type)
        source_con_list = []
        print('report_id_list', report_id_list)
        for i in range(len(report_id_list)):
            report_id = report_id_list[i]
            # 生成暂存意见书原始文件
            source_html_path = self.obtain_report_ex(dispute_type=dispute_type, report_id=report_id)
            source_con_list.append(source_html_path)
            # 对文本第一次处理
            # 一、删除替换部分
            handlecontent = HandleContent(html_ex_path, html_path)
            handlecontent.process_html()
            # 二、替换需要动态传递部分
            print('user_path:', user_path)
            if "'iw': 3" in str(user_path):
                for input_info_dict in user_path:
                    list_flag = isinstance(input_info_dict, dict)
                    if list_flag:
                        print('iw:', input_info_dict['iw'])
                        print(type(input_info_dict['iw']))
                        if input_info_dict['iw'] == 3:
                            input_value = input_info_dict['value']
                            print('填空内容为:', input_value)
                            if dispute_type == 'afdvc_children/' or dispute_type == 'divorce/':
                                hy = HunYin(html_path, input_value)
                                hy.process_content()
                            else:
                                input_option = input_info_dict['id_question']
                                ld = Labor(user_path, dispute_type, html_path, input_option, input_value)
                                ld.process_content()
        source_file_list = []
        for source_file in source_con_list:
            new_path = html_path + source_file.split('source_html_ex/')[-1]
            source_file_list.append(new_path)

        print('source_file_list:', source_file_list)
        return (report_id_list, source_file_list)

    def main(self):
        api_path = self.process_content()
        print(api_path)


class DeleteFiles(object):
    def delete_file(self, path):
        """
        删除文件夹下暂存文件
        :return:
        """
        for i in os.listdir(path):
            path_file = os.path.join(path, i)  # 取文件路径
            if os.path.isfile(path_file):
                os.remove(path_file)
        print('暂存文件已删除')


class ReportNameList(object):
    def __init__(self, report_name_list):
        self.report_name_list = report_name_list

    def report_input_list(self):
        return self.report_name_list
